#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <linux/input.h>
#include <sys/ioctl.h>
#include <tslib.h>

 
int distance(struct ts_sample_mt *point1,struct ts_sample_mt *point2)
{
    int x = point1->x-point2->x;
    int y = point1->y-point2->y;
    return x*x+y*y;
}
 
int main(int argc, char **argv)
{
 
    struct tsdev *ts ;
    int i ;
    int ret ;
    int max_slots ; 
    int touch_cnt ;
    int point_press[20] ;
	struct ts_sample_mt **samp_mt ;
    struct ts_sample_mt **pre_samp_mt ;
	struct input_absinfo slot;
 
    /*调用ts_setup打开设备节点*/    
    ts = ts_setup(NULL, 0) ;
	if (!ts) {
	    printf("ts_setup error\n");
	    return -1;
	}
 
    /*计算最多触摸点*/
	if (ioctl(ts_fd(ts), EVIOCGABS(ABS_MT_SLOT), &slot) < 0) {
		printf("ioctl EVIOGABS\n");
		ts_close(ts);
		return -1;
	}
	max_slots = slot.maximum + 1 - slot.minimum;
 

    /*初始化samp_mt*/ 
    samp_mt = malloc(sizeof(struct ts_sample_mt *));
	if (!samp_mt) {
		ts_close(ts);
		return -ENOMEM;
	}
	samp_mt[0] = calloc(max_slots, sizeof(struct ts_sample_mt));
	if (!samp_mt[0]) {
		free(samp_mt);
		ts_close(ts);
		return -ENOMEM;
	}


    /*初始化pre_samp_mt*/  
    pre_samp_mt = malloc(sizeof(struct ts_sample_mt *));
	if (!pre_samp_mt) {
		ts_close(ts);
		return -ENOMEM;
	}
	pre_samp_mt[0] = calloc(max_slots, sizeof(struct ts_sample_mt));
	if (!pre_samp_mt[0]) {
		free(pre_samp_mt);
		ts_close(ts);
		return -ENOMEM;
	}
 


    /*初始化pre_samp_mt的值*/
    for(i = 0; i < max_slots; i++)
        pre_samp_mt[0][i].valid = 0;
 
 
    while(1){
        ret = ts_read_mt(ts, samp_mt, max_slots, 1);// 读数据读到samp_mt结构体
        if (ret < 0) {
            printf("ts_read_mt error\n");
            ts_close(ts);
            return -1;
        }

        for(i = 0; i < max_slots; i++)
        {// 把samp_mt所有触点的值写入pre_samp_mt
            if(samp_mt[0][i].valid)
            {
                memcpy(&pre_samp_mt[0][i] , &samp_mt[0][i] ,sizeof(struct ts_sample_mt));
            }
        }
 
        touch_cnt = 0;
        for(i = 0; i < max_slots;i++)
        {
            if(pre_samp_mt[0][i].valid && pre_samp_mt[0][i].tracking_id != -1)
            
            point_press[touch_cnt++] = i;
        }
 
        if (touch_cnt == 2)
        {
            printf("diastance=%08d\n",distance(&pre_samp_mt[0][point_press[0]],&pre_samp_mt[0][point_press[1]]));
            //printf("diastance=%08d\n",distance(&pre_samp_mt[0][0],&pre_samp_mt[0][1]));

        }
    
    
    }
 
 
 
    return 0;
}